package com.bigknow.appstore.web.console.service.impl;

import com.bigknow.appstore.web.base.entity.FusionConfig;
import com.bigknow.appstore.web.base.entity.User;
import com.bigknow.appstore.web.base.service.IFusionService;
import com.bigknow.appstore.web.base.service.impl.SystemConfigService;
import com.bigknow.appstore.web.console.service.IDBServiceService;
import com.bigknow.fusion.common.FusionRuntimeException;
import com.bigknow.fusion.common.inf.server.appstore.FusionHandler;
import com.bigknow.fusion.common.model.appstore.DataService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * Created by 李科风 on 2016-09-19.
 */
@Service
public class DBServiceService implements IDBServiceService {

    @Autowired
    private IFusionService fusionService;

    @Autowired
    private SystemConfigService sysService;

    @Override
    public String loginFusion() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        FusionHandler handler = fusionService.getFusionHandler();
        FusionConfig cfg = sysService.getFusionConfig();

        if (isAppManager(user)) {
            return "http://" + cfg.getIp() + ":" + cfg.getWebPort() + "/login?target=user&username=" + user.getAccount() + "&password=" + handler.storeLogin(user.getId());
        }
        throw new FusionRuntimeException("用户无权申请服务");
    }

    @Override
    public List<DataService> getDataService() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        FusionHandler handler = fusionService.getFusionHandler();
        return handler.getDataService(user.getId());
    }

    private boolean isAppManager(User user) {
        return Arrays.binarySearch(user.getRoleIds().split(","), "2") != -1;
    }
}
